package cn.lopr.im.android.mvp.presenter;

import java.util.Map;

import cn.lopr.im.android.bean.CallbackResult;
import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.Constant;
import cn.lopr.im.android.common.OnCallBackListener;
import cn.lopr.im.android.common.app.Activity;
import cn.lopr.im.android.mvp.contact.ILoginContact;
import cn.lopr.im.android.mvp.model.LoginModel;
import cn.lopr.im.android.utils.GsonUtil;
import cn.lopr.im.android.utils.ParameterUtil;
import cn.lopr.im.android.utils.UiUtils;

/**
 * @author shuangyang7
 * @date 2020/12/19 11:51
 */
public class LoginPresenterImpl implements ILoginContact.ILoginPresenter {

    /**
     * 登录业务实现者，数据处理的操作者
     */
    private final ILoginContact.ILoginModel loginModel;
    private final Activity activity;
    /**
     * 视图接口对象
     */
    private final ILoginContact.ILoginView loginView;
    private String TAG = "";

    /**
     * 在构造方法中实例化model对象
     */
    public LoginPresenterImpl(Activity activity, ILoginContact.ILoginView loginView) {
        this.loginModel = new LoginModel();
        this.activity = activity;
        this.loginView = loginView;
    }

    @Override
    public void login() {
        String phone = loginView.getPhone();
        String password = loginView.getPassword();

        if (!UiUtils.isNetworkAvailable()) {
            loginView.showNetworkError();
            return;
        }

        if (ParameterUtil.checkParameter(phone, password)) {
            loginView.showVerifyFailed(Constant.PARAM_ERROR_MESSAGE);
            return;
        }

        loginView.showLoading(this.activity);    // 加载框
        //登录 ，需要处理数据，所有要在model中执行
        // 请求数据，返回数据
        loginModel.login(phone, password, new OnCallBackListener<CallbackResult<Map<String, Object>>, String>() {
            @Override
            public void success(CallbackResult<Map<String, Object>> result) {
                String token = (String) result.getData().get("token");

                User user = GsonUtil.mapToObject(result.getData().get("user"), User.class);
                loginView.loginSuccess(user);
                loginView.saveJwtKey("token", token);
                loginView.disLoading();
            }

            @Override
            public void failure(String errMsg) {
                //在给视图页面返回验证失败的结果
                loginView.disLoading();
                loginView.showVerifyFailed(errMsg);
            }

        });
    }

    @Override
    public void isLogin() {
        String token = loginView.getToken(this.activity);
        loginModel.isLogin(token, new OnCallBackListener<CallbackResult<User>, String>() {
            @Override
            public void success(CallbackResult<User> data) {
                loginView.isLogin(data.getData());
            }

            @Override
            public void failure(String errMsg) {

            }
        });

    }
}
